var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
var jwt = require('jsonwebtoken');//引入jwt生成token
var secretKey = require('../cipher/key');//密钥
const SMSClient = require('@alicloud/sms-sdk'); // 引入依赖阿里云
const nodemailer = require('nodemailer');
const smsClient = new SMSClient({
    accessKeyId: 'LTAI5tF3M4t4gUQrYDK33Vqz',
    secretAccessKey: 'poiCHZxk4zKdfdW2SuM1Km3GWvFkTQ'
});
const { worksModel, VPCCmodel, usersModel, complaintModel, UserIdentityModel, FeedbackIssueModel, xmmodel, schoolInfoModel, waterModel } = require('../db/index')
/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', { title: 'Express' });
});
// 登录授权
router.post('/login', async (req, res) => {
    let { usersname, password } = req.body;
    const userData = await usersModel.findOne({ usersname })
    if (!userData) {
        res.send({
            code: 400,
            msg: '账号不存在',
        });
        return
    }
    if (userData.password !== password) {
        res.send({
            code: 400,
            msg: '密码错误',
        });
        return
    }
    const accessToken = jwt.sign(req.body, secretKey, { expiresIn: '2h' });
    const refreshToken = jwt.sign(req.body, secretKey, { expiresIn: '7d' });
    res.send({
        code: 200,
        msg: '登录成功',
        userInfo: { usersname: userData.usersname },
        accessToken,
        refreshToken
    });
});
// 验证token
router.get('/loginInfo', async (req, res) => {
    const authorization = req.headers.authorization
    console.log(authorization);

    if (!authorization) {
        res.send({
            code: 400,
            msg: "用户未登录",
        })
        return
    }
    try {
        const token = authorization.split(' ')[1]
        const data = jwt.verify(token, secretKey);
        // 相应的事件成立
        res.send({
            code: 200,
            data,
            msg: '已登录,accessToken有效'
        })
    } catch (error) {
        console.error('Token verification error:', error);  // 打印错误日志
        res.send({
            code: 401,
            msg: "token失效,请重新登录",
            error: error
        })
    }
});
// 刷新access_Token接口 接收前端传递的token
router.get('/refresh', async (req, res) => {
    try {
        const data = jwt.verify(req.query.token, secretKey)
        const userData = await usersModel.findOne({ usersname: data.usersname })
        const accessToken = jwt.sign({ usersname: userData.username, password: userData.password }, secretKey, { expiresIn: '2h' });
        const refreshToken = jwt.sign({ usersname: userData.username, password: userData.password }, secretKey, { expiresIn: '7d' });
        res.send({
            code: 200,
            msg: '已登录,双token重新生成',
            userInfo: { usersname: userData.usersname },
            accessToken,
            refreshToken
        })
    } catch (error) {
        console.error('Token refresh error:', error);  // 打印错误日志
        res.send({
            code: 401,
            msg: "refresh_Token失效,请重新登录",
            error: error
        })
    }
});
// 注册账号
router.post('/user', async (req, res) => {
    await usersModel.create(req.body)
    res.send({
        code: 200,
        msg: '注册成功'
    })
})

// 创建邮件传输器
const transporter = nodemailer.createTransport({
    service: 'qq', // 使用 qq
    auth: {
      user: '3193511917@qq.com', // 你的邮箱地址
      pass: 'cronahgnqvaxddcf', // QQ 邮箱授权码
    },
  });
  
// 发送验证码
router.get('/register', async (req, res) => {
    // 1. 生成6位随机验证码
    const verCode = Math.floor(100000 + Math.random() * 900000).toString();
    console.log(req.query);
    let { email } = req.query
    if  (email && email.includes('@')) {
          // 配置邮件内容
        const mailOptions = {
            from: '3193511917@qq.com', // 发件人邮箱
            to: email, // 收件人邮箱
            subject: '校园食品安全监督平台用户注册', // 邮件主题
            
            html: `<b>如果不是本人操作请谨慎识别发送验证码: ${verCode} </b>`,
          };

          try {
            // 发送邮件
            await transporter.sendMail(mailOptions);
            res.send({
              code:200,
              verCode
            })
          } catch (error) {
            console.error('Error sending email:', error);
            res.send({
              code:500
            })
          }


    } else if (email) {
        await smsClient.sendSMS({
            PhoneNumbers: email, // 手机号（国内需加86，如 "13800138000"）
            SignName: '阿里云短信测试', // 控制台申请的签名
            TemplateCode: 'SMS_154950909', // 控制台申请的模板CODE
            TemplateParam: `{"code":"${verCode}"}` // 替换模板中的变量
        })
        res.send({
            code: 200,
            msg: '发送成功',
            verCode
        })
    }


})

// 张贵天 学校详情
router.get('/list', async (req, res) => {
    const data = await schoolInfoModel.find()
    res.send({
        code: 200,
        data: data
    })
})

//唐佑超
router.get('/getstu', async (req, res) => {
    let stu = await xmmodel.find();
    res.send({
        stu
    })
})

//石路涛 
router.post('/upload', (req, res) => {
    let form = new multiparty.Form()
    form.uploadDir = 'upload'
    form.parse(req, (err, a, img) => {
        res.send({
            code: 200,
            path: 'http://localhost:3009/' + img.file[0].path
        })
    })
})
router.post('/addc', async (req, res) => {
    await complaintModel.create(req.body)
    res.send({
        code: 200,
        msg: '添加成功'
    })

})

router.get('/complaint', async (req, res) => {
    let { time, type } = req.query
    let arr = [{}]
    if (time) {
        arr.push({ time: new RegExp(time) })
    }
    if (type) {
        arr.push({ type })
    }
    let list = await complaintModel.find({ $and: arr })
    res.send({
        list
    })
})
router.post('/delct', async (req, res) => {
    let { _id } = req.body
    await complaintModel.deleteOne({ _id })
    res.send({
        code: 200,
        msg: '删除成功'
    })
})
// 尤帅凯
router.get('/userIdentity', async (req, res) => {
    const data = await UserIdentityModel.find()
    res.send({
        code: 200,
        data
    })
})

router.post('/picture', async (req, res) => {
    let { cate, conText, img, phone } = req.body
    const data = await FeedbackIssueModel.create({ cate, conText, img, phone })
    res.send({
        code: 200,
        data
    })
})

// 杨佳乐
router.get('/VPCC', async (req, res) => {
    let { kweyword = "" } = req.query
    console.log(kweyword);

    if (kweyword) {
        const data = await VPCCmodel.findOne({ NAME: kweyword })
        res.send({
            code: 200,
            data
        })
    } else {
        res.send({
            data: {
                NAME: "XXX",
                NickName: "XXX",
                telplate: "XXX",
                sex: '',
                childName: "XXX",
                ChildtTes: "XXX"
            }
        })
    }
})
// 搜索
router.get('/waterlist', async (req, res) => {
    let { keyword } = req.query
    if (keyword) {
        let waterlist = await waterModel.find({ name: new RegExp(keyword) })
        res.send({
            status: 200,
            waterlist
        })
    } else {
        let waterlist = await waterModel.find()
        res.send({
            status: 200,
            waterlist
        })
    }
})



module.exports = router;
